package com.fm.magic.net.chrome.domain;

import com.fm.base.json.JsonObject;
import com.fm.commons.json.BasicJsonObject;
import com.fm.magic.net.chrome.ChromeTab;
import com.fm.magic.net.chrome.type.FrameId;
import com.fm.magic.net.chrome.type.TransitionType;
import com.neovisionaries.ws.client.WebSocket;

/**
 * @author leo.li
 */
public class Page {
    private ChromeTab tab;

    public Page(ChromeTab tab) {
        this.tab = tab;
    }

    public FrameId navigate(String url, String referrer, TransitionType transitionType) {
        JsonObject params = new BasicJsonObject().append("url", url);
        if (referrer != null) {
            params.append("referrer", referrer);
        }
        if (transitionType != null) {
            params.append("transitionType", transitionType.value);
        }
        JsonObject command = new BasicJsonObject()
            .append("id", tab.getNextRequestId())
            .append("method", "Page.navigate")
            .append("params", params);
        WebSocket socket = tab.getWebSocket().sendText(command.toLiteJson());
        synchronized (socket) {
            try {
                socket.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }
}
